<template>
  <div class="article-lists">
    <el-card class="!border-none" shadow="never">
      <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
        <!-- <el-form-item label="主营业务">
          <el-select
              class="w-80"
              v-model="queryParams.cate_id"
              placeholder="请选择"
              clearable
          >
            <el-option
                v-for="item in optionsData.product_cate_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="渠道姓名">
          <el-input
              class="w-[280px]"
              v-model="queryParams.name"
              clearable
          />
        </el-form-item>

        <el-form-item label="渠道手机号">
          <el-input
              class="w-[280px]"
              v-model="queryParams.account"
              clearable
          />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select class="w-[280px]" v-model="queryParams.is_enable">
            <el-option label="全部" value/>
            <el-option label="启用" :value="1"/>
            <el-option label="停用" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="协议状态">
          <el-select class="w-[280px]" v-model="queryParams.protocal_status">
            <el-option label="全部" value/>
            <!-- <el-option label="未发起" :value="0"/> -->
            <el-option label="待签署" :value="1"/>
            <el-option label="签署成功" :value="2"/>
            <el-option label="签署失败" :value="3"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属城市">
            <el-select-v2
                  v-model="queryParams.area_id"
                  filterable
                  clearable
                  :options="optionCity"
                  placeholder="请选择"
                  class="w-[280px]"
                  :height="280"
              />
				</el-form-item>
        <el-form-item label="限时权益">
          <el-select class="w-[280px]" v-model="queryParams.is_limit_time_benefit">
            <el-option label="全部" value/>
            <el-option label="是" :value="1"/>
            <el-option label="否" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="企业认证">
          <el-select class="w-[280px]" v-model="queryParams.is_authentication">
            <el-option label="是" :value="1"/>
            <el-option label="否" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select class="w-[280px]" v-model="queryParams.interests_id">
            <el-option label="全部" value/>
            <el-option v-for="item in vip_list" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never">
      <!-- <div>
        <router-link
            v-perms="['channel.channel/add', 'channel.channel/add:edit']"
            :to="{
                        path: getRoutePath('channel.channel/add:edit')
                    }"
        >
          <el-button type="primary" class="mb-4">
            <template #icon>
              <icon name="el-icon-Plus"/>
            </template>
            新增渠道
          </el-button>
        </router-link>
      </div> -->
      <el-table size="large" v-loading="pager.loading" :data="pager.lists">
        <el-table-column label="序号(ID)" prop="id" min-width="90"/>
        <el-table-column label="所属城市" min-width="120">
          <template #default="{ row }">
            <span v-if="row.area_id" v-city="row.area_id"></span>
          </template>
        </el-table-column>
        <el-table-column label="所属场地" min-width="160">
          <template #default="{ row }">
            {{row?.office_place?.name}}
          </template>
        </el-table-column>
        <el-table-column label="姓名" min-width="100" prop="real_name"/>
        <el-table-column label="头像" min-width="160">
          <template #default="{ row }">
            <image-contain
                v-if="row.avator"
                :src="row.avator"
                :width="60"
                :height="45"
                :preview-src-list="[row.avator]"
                preview-teleported
                fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column label="职务" min-width="160" prop="position"/>
        <el-table-column
            label="微信号"
            prop="wechat_no"
            min-width="160"
        />
        <el-table-column
            label="手机号"
            prop="account"
            min-width="160"
        />

        <el-table-column label="渠道等级" min-width="160">
          <template #default="{ row }">
           {{row.start_level}}星
          </template>
        </el-table-column>
        <el-table-column label="助融分" prop="total_score" min-width="160" sortable show-tooltip-when-overflow/>
        <el-table-column label="公司" prop="company_name" min-width="160" show-tooltip-when-overflow/>
        <el-table-column label="地址" prop="company_address" min-width="160" show-tooltip-when-overflow/>

        <el-table-column label="主营业务" min-width="160">
          <template #default="{ row }">
            {{ localGetProductCateText(row.product_cate_arr) }}
          </template>
        </el-table-column>
        <el-table-column label="关联产品" min-width="100">0</el-table-column>
        <el-table-column label="成交" min-width="100">0</el-table-column>
        <el-table-column label="启用状态" min-width="120">
          <template #default="{ row }">
             <span  v-if="row.is_enable == 0" style="color:red">
               停用
             </span>
            <span  v-if="row.is_enable == 1">
                启用
            </span>
          </template>
        </el-table-column>

        <el-table-column label="协议状态" min-width="120">
          <template #default="{ row }">
             <span  v-if="row.protocal_status == 0">
               未发起
             </span>
            <span  v-if="row.protocal_status == 1">
              待签署
            </span>
            <span  v-if="row.protocal_status == 2">
                签署成功
            </span>
            <span  v-if="row.protocal_status == 3">
                签署失败
            </span>
          </template>
        </el-table-column>
        <el-table-column label="限时权益" min-width="120">
          <template #default="{ row }">
            <span v-if="row.is_limit_time_benefit == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="企业认证" min-width="120">
          <template #default="{ row }">
            <span v-if="row.is_authentication == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="渠道会员等级" min-width="120">
          <template #default="{ row }">
            <span v-if="row.interests_id == 1">白银会员</span>
            <span v-if="row.interests_id == 2">黄金会员</span>
            <span v-if="row.interests_id == 3">钻石会员</span>
            <span v-if="row.interests_id == 0">否</span>
          </template>
        </el-table-column>
        <el-table-column label="是否为付费渠道" min-width="140">
          <template #default="{ row }">
            <el-switch v-model="row.is_paid" v-perms="['user.agent/openGroup']" @change="togglePaid(row.id, row.is_paid, row.area_id)" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="优势渠道" min-width="120">
          <template #default="{ row }">
            <el-switch v-model="row.is_advantaged" v-perms="['user.agent/openGroup']" @change="toggleAdvantaged(row.id, row.is_advantaged, row.area_id)" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="是否自营" min-width="120">
          <template #default="{ row }">
            <el-switch v-model="row.is_official " @change="toggleOffcial(row.id, row.is_official, row.area_id)" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
           <el-button v-perms="['channel.channel/edit', 'channel.channel/add:edit']" type="primary" link >
              <router-link :to="{ path: getRoutePath('channel.channel/add:edit'), query: { id: row.id, area_id: row.area_id  } }" > 编辑 </router-link>
            </el-button>
            <!-- <el-button v-perms="['channel.channel/delete']" type="danger" link @click="handleDelete(row.id)" > 删除 </el-button> -->
            <!-- <el-switch v-perms="['channel.channel/updateStatus']" v-model="row.is_enable" :active-value="1" :inactive-value="0" @change="changeStatus($event, row.id)" /> -->
			      <!-- <el-button v-if="row.protocal_status==0||row.protocal_status==3" v-perms="['channel.channel/sendSign']" type="primary" link @click="handleCheck(row.id,row.account)">协议签署</el-button> -->
		  </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <pagination v-model="pager" @change="getLists"/>
      </div>
    </el-card>
	<check_demand v-model:show="checkState.show" :value="checkState.value" @confirm="handleConfirmCheck"></check_demand>
  </div>
</template>
<script lang="ts" setup name="channelLists">
import {channelLists, channelDelete, channelStatus, sendSign, updatePaidStatus, updateAdvantagedStatus, setOfficial} from '@/api/channel/channel'
import { getVipList } from '@/api/vip'
import {usePaging} from '@/hooks/usePaging'
import {getRoutePath} from '@/router'
import feedback from '@/utils/feedback'
import check_demand from './check_demand.vue';
import useAppStore from '@/stores/modules/app'

const useApp = useAppStore()
const optionCity:any = [{label: '全部',value:''}].concat(useApp.optionCity);
const checkState = reactive({
	show: false,
	value: '',
	id: null
})

const vip_list:any = ref([])
const getVipLists = async () => {
  const res = await getVipList()
  console.log(res)
  vip_list.value = res.list;
}
getVipLists()

const handleCheck = (id:any,value:any) => {
	checkState.show = true
	checkState.id = id
	checkState.value = value
}

const handleConfirmCheck = async (value : any) => {
	const data = await sendSign({ id: checkState.id });
	getLists()
	checkState.show = false
	getLists()
}

const handleSign = async (id : number) => {
	await feedback.confirm("确认签署？")
	try{
		const data = await sendSign({ id });
		getLists()
	}catch(e){
		console.log(e);
		//TODO handle the exception
	}
}
	
const queryParams:any = reactive({
  cate_id: '',
  name: '',
  account: '', //手机号
  is_enable: '',
  protocal_status: '', //协议状态
  area_id: '',
  is_limit_time_benefit: '',
  is_authentication: '',
  interests_id: ''
})

const {pager, getLists, resetPage, resetParams} = usePaging({
  fetchFun: channelLists,
  params: queryParams
})

const togglePaid = async (id:any,status:any, area_id:any) => {
    console.log(status)
    await updatePaidStatus({
        id,
        area_id,
        is_paid: status
    })
    getLists()
}

const toggleAdvantaged = async (id:any,status:any, area_id:any) => {
    console.log(status)
    await updateAdvantagedStatus({
        id,
        area_id,
        is_advantaged: status
    })
    getLists()
}

const toggleOffcial = async (id:any,status:any, area_id:any) => {
  await setOfficial({
    id,
    area_id,
    is_official: status
  })
  getLists()
}

const changeStatus = async (is_enable: any, id: number) => {
  try {
    if(is_enable == 0){  //如果停用
      await feedback.confirm("停用之后，该用户不能切换渠道身份，是否确认停用？")
    }else if(is_enable == 1){ //如果启用
      await feedback.confirm("启用之后，该用户可切换渠道身份，是否确认启用？")
    }

    try {
      await channelStatus({id, is_enable})
      getLists()
    } catch (error) {
      getLists()
    }
  }catch (error) {
    getLists()
  }
}

const handleDelete = async (id: number) => {
  await feedback.confirm('确定删除该渠道？')
  await channelDelete({id})
  getLists()
}


const localGetProductCateText = (productCateArr: Array<any>): string => {
  let productCateText = ''
  productCateArr.forEach((item, index) => {
    productCateText += (item?.name)+'/'
  })
  return productCateText.replace(/[\\//]$/, "");
}


/*
const localGetRepaymentTypeText = (repaymentTypes: number[]| null): string => {
  //1.先息后本 2.等额本息 3.等额本金
  let repaymentTypeStr = ''
  if (!isEmpty(repaymentTypes)) {
    (repaymentTypes as number[]).forEach((item,index )  => {
      if (item == 1) {
        repaymentTypeStr += '先息后本/'
      } else if (item == 2) {
        repaymentTypeStr += '等额本息/'
      } else if (item == 3) {
        repaymentTypeStr += '等额本金/'
      }

    })
  }
  return repaymentTypeStr.slice(0, -1)
}



*/

onActivated(() => {
  getLists()
})
const route = useRoute()
if (route.query.name) {
  queryParams.name = route.query.name
}

getLists()
</script>
